#include <stdio.h>
#include <locale.h>
#include <getopt.h>
#include <ctype.h>
#include "pircode.h"

int main(int argc, char* argv[]) {
    wchar_t buffer[256];
    pir_t result;
    char pir[PIR_CODE_LENGTH];
    wchar_t delim = '\0';

    setlocale(LC_ALL, "");
    int index;
    int c;

    opterr = 0;

    memset(pir, 0, 3);

    while ((c = getopt (argc, argv, "c:d:")) != -1) {
        switch (c)
        {
            case 'c':
                if(strlen(optarg) == 0 || strlen(optarg) > 3) {
                    fprintf(stderr, "Invalid PIR code: Must have length 1 to 3.\n");
                    return 1;
                }
                strncpy(pir, optarg, PIR_CODE_LENGTH);
                break;
            case 'd':
                delim = btowc(optarg[0]);
                break;
            case '?':
                if (optopt == 'c')
                    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
                else if (isprint(optopt))
                    fprintf (stderr, "Unknown option `-%c'.\n", optopt);
                else
                    fprintf (stderr,
                             "Unknown option character `\\x%x'.\n",
                             optopt);
                return 1;
            default:
                abort ();
        }
    }

    // TODO add str equivalent of wcssatdfn to string-utility and check if PIR code is only decimal digits

    while (fgetws(buffer, 256, stdin) != NULL) {
        // TODO Skip empty lines? Would be PIR code 0 false-positive otherwise
        pir_code_init(&result);
        if(delim != '\0') {
            wchar_t * found = wcschr(buffer, delim);

            if(found != NULL) {
                size_t initial_string = found - buffer;
                pir_code_writen(buffer, initial_string, &result);
            } else {
                pir_code_write(buffer, &result);
            }
        } else {
            pir_code_write(buffer, &result);
        }
        if(strncmp(result.pir, pir, strlen(pir) <= 3 ? strlen(pir) : 3) == 0) {
            wprintf(buffer);
        }
    }

    return 0;
}
